/**
*	oa审批事项列表页面
*
*/

require(['../js/appConf','../js/bsConfig', '../js/duties','../js/bsPlugins'], function() {
    // Configuration loaded now, safe to do other require calls
    // that depend on that config.
    
    require(['init','dataTable','dataTables-jqueryui','jqueryValidate','bsButton','bsButtonEvent','bsMsgServ','domReady!'],
    	function(init,dataTable,ui,validate,bsButton,bsButtonEvent,bsMsgServ,doc) {
		
    	var rootid = 'issue-main'
    	
    	var dg_table 
    	
    	var selected = [];
    	
    	//业务列表-表单容器对象
    	var list_c = ' div.list-detail'
    		
    	//当前业务模块代码
    	var current_bizcode 
    	
    	//当前选中行
    	var curent_selectRow
    	
		var funcDef = {
    	
    	/**
    	 * 初始化侧边栏导航
    	 */
    	initNav:function(){
    		var _param = {
    			url:'/'+init.getSite()+'/permission/query/getUserDutiesMenu.action',
    			success:function(data){
    				if(window.console){
    					console.log('menu data: ' + data.length);
    				}
    				var _el = $('#' + rootid + ' #left-nav')
    				if(_el.length==1){
    					var _html = '';
    					$.each(data,function(i,o){
    						
    						_html+='<li>'+
    							   '<a class="left-nav-btn" href="javascript:void(0);" id="'+o.bizcode+'">'+ 
    							   o.name +
    							   '</a>'+
    							   '</li>'
    						
    					})
    					
    					if(_html){
    						_el.empty();
    						_el.append(_html);
    						
    						funcDef.btn_listenner();
    					}
    				}
    			}
    		}
    		$.ajax(_param)
    	},
    	/**
    	 * 初始化列表
    	 * @param _options.module	模块代码
    	 * @param _options.ajax		server端数据访问方法
    	 * @param _options.paging	分页标志
    	 * @param _options.columns	缺省列
    	 */
    	initList:function(_options){
    		
    		 
    		var _default = {
    			processing: true,
    			serverSide: true,
    			//searching: false,
    			 "lengthMenu": [[10, 15, 25, 50, -1], [10, 15, 25, 50, "All"]],
    			rootid: null,
    			gridSelector: 'dg-list',
    			method: 'getListDomain',    			
    			//paging:true,
    			bPaginate: true,
    			//pagingType: "full_numbers",
    			pageLength: 15,
    			//sDom:'lfrtip',//default layout
    			sDom:'tilp',
    			rowId:'id',
    			columns: [
    				{"data":null,"title":"序号"},
    				{ "data": "bizno","title":"业务编码"},
					//{ "事项类型": "bizname" },
					{ "data": "name" ,"title":"事项名称"},
					{ "data":  "apply_deptname","title":"申请科室"},
					{ "data":  "apply_name","title":"申请人员"},
					{ "data": "apply_date" ,"title":"申请时间"}
					//{ "当前环节": "status" },
					//{ "附件": "archive" }
    			],
    			
    			"oLanguage": {//下面是一些汉语翻译
                    "sProcessing":   "处理中...",
				    "sLengthMenu":   "每页 _MENU_ 条记录",
				    "sZeroRecords":  "没有匹配结果",
				    "sInfo":         "第 _START_ 至 _END_ 条，共 _TOTAL_ 条",
				    "sInfoEmpty":    "显示第 0 至 0 条，共 0 条",
				    "sInfoFiltered": "(由 _MAX_ 条结果过滤)",
				    "sInfoPostFix":  "",
				    "sSearch":       "搜索:",
				    "sUrl":          "",
				    "sEmptyTable":     "表中数据为空",
				    "sLoadingRecords": "载入中...",
				    "sInfoThousands":  ",",
				    "oPaginate": {
				        "sFirst":    "首页",
				        "sPrevious": "上页",
				        "sNext":     "下页",
				        "sLast":     "末页"
				    },
				    "oAria": {
				        "sSortAscending":  ": 以升序排列此列",
				        "sSortDescending": ": 以降序排列此列"
				    }
                }
                ,"columnDefs": [ {
		            "searchable": false,
		            "orderable": false,
		            "targets": 0
		        } ],
		        
		        //"order": [[ 1, 'asc' ]]//定义初始排序事件，触发列的回写事件
                "fnDrawCallback": function(){
				　　var api = this.api();
				　　var startIndex= api.context[0]._iDisplayStart;//获取到本页开始的条数
				　　api.column(0).nodes().each(function(cell, i) {
				　　　　cell.innerHTML = startIndex + i + 1;
				　　}); 
				}
				,
				"rowCallback": function( row, data ) {
		            if ( $.inArray(data.DT_RowId, selected) !== -1 ) {
		                $(row).addClass('selected');
		            }
		        }
                //"iDisplayLength": 10//每页显示10条数据
                
                //"bAutoWidth": true //宽度是否自动，感觉不好使的时候关掉试试
    		}
    		
    		
    		var def = $.extend({},_default,_options);
    		
    		if(_options.module){    			
    			_options.module = funcDef.changeBizcode(_options.module);
    			if(window.console){
    				console.log('module code: ' + _options.module);
    			}
    		}
    		//_options.module = 'tempDrugPurchase';
    		if(_options && _options.module){
    			def.ajax = {
    				url:'/'+init.getSite()+'/'+_options.module+'/query/'+def.method+'.action',
    				
    				type:'post'    			
    			}
    			if(dg_table){
    				dg_table.destroy();
    			}
    			dg_table =$('#'+rootid + ' table.'+def.gridSelector).DataTable(def); 
    			
    			dg_table.on('click', 'tr', function () {
			        var id = this.id;
			        var index = $.inArray(id, selected);			        
			 
			        if ( index === -1 ) {
			            selected.push( id );
			        } else {
			            selected.splice( index, 1 );
			        }
			 		
			        $(this).toggleClass('selected');
			        
			        
			        //funcDef.tableClick({bizcode:_options.module})
			        
			       
			        funcDef.tableClick({bizcode:_options.module,id:id});
			        
			        
			    } );
			    
			     //更新按钮
    			funcDef.redrawBtn({
    				bizcode:_options.module.substring(2),
    				bizType:1,	//流程业务
    				btnType:'list',	//edit 页面
    				container:'issue-main div.btn-container'
    			})
    		}
    	}
    	,
    	/**
    	 * 按钮事件定义
    	 */
    	btn_listenner:function(){
    		var _btn = $('#'+rootid +' a.left-nav-btn')
    		if(_btn.length>0){
    			_btn.unbind('click');
    			_btn.bind('click',funcDef.navClick)
    		}
    	}
    	
    	,
    	/**
    	 * 业务类型点击事件
    	 */
    	navClick:function(e){
    		
    		//选中状态 class 调整
    		$('#' + rootid + ' #left-nav li').removeClass('active');
    		$(e.currentTarget).closest('li').addClass('active');
    		
    		//获取选中对象类型
    		var _navType = init.getNavType(e);
    		if(window.console){
				console.log('module: ' + _navType);
			}
    		
    		//获取容器对象
			var _c =$('#' + rootid +list_c)
    		
			//刷新容器对象，变更数据
			if(_c){
				//清除原有内容
				_c.empty();
				
				var _html = '<table class="dg-list" cellspacing="0" width="100%"></table>';
				_c.append(_html);
			}			
			
			current_bizcode = funcDef.changeBizcode(_navType);
    		funcDef.initList({module:_navType});
    	}
    	,
    	
    	clearDetail:function(){
    		var _c =$('#' + rootid +list_c)
    			
    			if(_c){
    				//清除原有内容
    				_c.empty();
    			}
    	}
    	,
    	/**
    	 * 业务列表点击事件
    	 * @param _options.bizcode	业务代码
    	 * @param _options.id		记录id
    	 */
    	tableClick:function(_options){
    		if(_options &&　_options.bizcode){
    			
    			//查找容器对象
    			var _c =$('#' + rootid +' div.list-detail')
    			
    			if(_c){
    				//清除原有内容
    				_c.empty();
    				
    				//加载页面
    				var _url = '/'+init.getSite()+'/'+_options.bizcode+'/query/getPage.action?code=bsEditDlg'
    				_c.load(_url)
    				
    				//加载数据
    				var _param = {
    					url : '/'+init.getSite()+'/'+_options.bizcode+'/query/getOne.action',
    					data:{id:_options.id},
    					success:function(data){
    						
    						var _form = $('#' + rootid +' div.list-detail form.main-form')
    						   						
    						if(data){
    							_form.form('load',data);
    						}    						
    					}
    				}
    				$.ajax(_param);
    			}
    			
    			//更新按钮
    			funcDef.redrawBtn({
    				bizcode:_options.bizcode.substring(2),
    				bizType:1,	//流程业务
    				btnType:'edit',	//edit 页面
    				container:'issue-main div.btn-container'
    			})
    		}
    	}
    	,
    	
    	/**
    	 * 更新按钮
    	 * @param _options.bizcode	业务编码
    	 * @param _options.btnType		按钮类型(list,edit,view)
    	 * @param _options.bizType	业务类型(0:normal,1:flow,2:audit)
    	 * @param _options.container 按钮容器对象
    	 */
    	redrawBtn:function(_options){
    		
    		
    		var _btn ;
    		if(_options && _options.btnType){
    			
	    		_btn = bsButton.getBtn(_options);
	    				
    		}
    		
    		if(_btn){
    			
    			$('#'+_options.container + ' button').unbind('click');
    			$('#'+_options.container).empty();
    			$('#'+_options.container).append(_btn);
    			
    			//绑定按钮事件
    			$('#'+_options.container + ' button').bind('click',funcDef.btnClick);
    		}
    		
    	}
    	,
    	btnClick:function(e){
    		var _btnConfig ={
    			listAdd:funcDef.add
    		}
    		init.applyBtnEvt({btnEvt:e,btnConfig:_btnConfig})
//    		bsMsgServ.msgSlide();
    	}
    	,
    	
    	add:function(e){
    		
    		var _url = '/'+current_bizcode+'/query/getPage.action?code=bsEditDlg'
    		bsButtonEvent.add({
    			url:_url,
    			container:'issue-main div.list-detail',
    			formInit:null,
    			evt:e
    		})
    	}
    	,
    	/**
    	 * 验证表单
    	 * @param _options.code		业务编码
    	 */
    	validateForm:function(_options){
    		
    		var ret = false
    		//判断传入编码是否为空
    		if(_options && _options.code){
    			
    			//根据业务当前流程节点状态获取字段配置
    			var rules = init.getFieldRule({bizcode:_options.code,activitiId:_options.activitiId})
    			
    			ret = $('#' + rootid + ' form.main-form').validate(rules);    			
    		}
    		return ret;
    	}
    	,
    	
    	/**
    	 * 生成表单验证规则
    	 * @param _options.data		规则字段配置
    	 */
    	generateFormRule:function(_options){
    		
    		var _rule = {
    			errorElement : 'span',  
	            errorClass : 'help-block',  
	            focusInvalid : true
    		}
    		
    		if(_options.data){
    			
    		}
    		
    	}
    	,
    	/**
    	 * 初始化表单按钮及页面元素
    	 * @param _options.code		业务编码
    	 */
    	initForm:function(_options){
    		//判断传入编码是否为空
    		if(_options && _options.code){
    			
    			//根据模块代码及流程节点定义，获取节点按钮配置
    			
    		}
    	}
    	,
    	
    	changeBizcode:function(code){
    		
    		var _m;
    		 //缓存当前模块代码
    		if(code){
    			if(code.substring(0,2)=='oa'){
    				_m = code.substring(2);
    			}else{
    				_m = code;
    			}
    		}
    		return 'bs' + _m;
	        
    	}
		
	};
		funcDef.initNav();
		
		
    })
})
